logo

Crate ctr

source · []
Expand description

Generic implementations of CTR mode for block ciphers.

Mode functionality is accessed using traits from re-exported cipher crate.

⚠️ Security Warning: Hazmat!

This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity is not verified, which can lead to serious vulnerabilities!

Example

use aes::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
use hex_literal::hex;

type Aes128Ctr64LE = ctr::Ctr64LE<aes::Aes128>;

let key = [0x42; 16];
let iv = [0x24; 16];
let plaintext = *b"hello world! this is my plaintext.";
let ciphertext = hex!(
    "3357121ebb5a29468bd861467596ce3da59bdee42dcc0614dea955368d8a5dc0cad4"
);

// encrypt in-place
let mut buf = plaintext.to_vec();
let mut cipher = Aes128Ctr64LE::new(&key.into(), &iv.into());
cipher.apply_keystream(&mut buf);
assert_eq!(buf[..], ciphertext[..]);

// CTR mode can be used with streaming messages
let mut cipher = Aes128Ctr64LE::new(&key.into(), &iv.into());
for chunk in buf.chunks_mut(3) {
    cipher.apply_keystream(chunk);
}
assert_eq!(buf[..], plaintext[..]);

// CTR mode supports seeking. The parameter is zero-based _bytes_ counter (not _blocks_).
cipher.seek(0u32);

// encrypt/decrypt from buffer to buffer
// buffer length must be equal to input length
let mut buf1 = [0u8; 34];
cipher
    .apply_keystream_b2b(&plaintext, &mut buf1)
    .unwrap();
assert_eq!(buf1[..], ciphertext[..]);

let mut buf2 = [0u8; 34];
cipher.seek(0u32);
cipher.apply_keystream_b2b(&buf1, &mut buf2).unwrap();
assert_eq!(buf2[..], plaintext[..]);

Re-exports

pub use cipher;
pub use flavors::CtrFlavor;

Modules

CTR mode flavors

Structs

Generic CTR block mode instance.

Type Definitions

CTR mode with 32-bit big endian counter.
CTR mode with 32-bit little endian counter.
CTR mode with 64-bit big endian counter.
CTR mode with 64-bit little endian counter.
CTR mode with 128-bit big endian counter.
CTR mode with 128-bit little endian counter.